package com.xnyzc.lhy.gateway.config;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.xnyzc.lhy.common.component.didi.DiDiUrlConstant;
import com.xnyzc.lhy.common.entity.DiDiRv;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.penum.EDiDiErrorCode;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.util.CheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:
 * @Author: scootXin
 * @Date: 2019/1/2 9:15
 */
@Slf4j
@Component
public class PangZuulExceptionFilter extends ZuulFilter {
    private static final String ERROR_STATUS_CODE_KEY = "error.status_code";

    @Override
    public String filterType() {
        return "error";
    }

    @Override
    public int filterOrder() {
        //需要在默认的 SendErrorFilter 之前
        // Needs to run before SendErrorFilter which has filterOrder == 0
        return -1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        Object e = ctx.get("throwable");

        try {
            if (e != null && e instanceof ZuulException) {
                ZuulException zuulException = (ZuulException) e;

                // Remove error code to prevent further error handling in follow up filters
                // 删除该异常信息,不然在下一个过滤器中还会被执行处理
                ctx.remove("throwable");

                HttpServletRequest request = ctx.getRequest();
                // 根据具体的业务逻辑来处理
                ctx.setResponseStatusCode(HttpStatus.OK.value());

                //设置response
                HttpServletResponse response = ctx.getResponse();
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");

                String url = request.getServletPath();
                log.error("zuul exception,请求地址 {},异常信息：{}", url, zuulException.getCause().getMessage());
                if (CheckUtil.strIsNotEmpty(url) && url.startsWith(DiDiUrlConstant.requestUrlPrefix)) {
                    response.getWriter().println(DiDiRv.wrap(EDiDiErrorCode.gatewayDeny, EDiDiErrorCode.gatewayDeny.getDesc(), new JSONObject()));
                } else {
                    response.getWriter().println(Rv.wrap(EErrorCode.gatewayDeny, EErrorCode.gatewayDeny.getDesc(), null));
                }
            }

        } catch (Exception ex) {
            String error = "Error during filtering[ErrorFilter]";
            log.error(error, e);
        }

        return null;
    }

}
